# -*- encoding:utf-8 -*-
# __author__ = 'chenyongbing'
# __poject__ = 'ops_platform'
# __datetime__ = '2022/2/21'
# __name__ = 'wxlogin.py'
import requests
import logging
# Create your code here.


class WxHelper():
    def __init__(self, corpid, agentid,corpsecret):
        self.corpid = corpid
        self.agentid = agentid
        self.corpsecret = corpsecret
        self.access_token = self._get_access_token()

    def _get_access_token(self):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}'.format(
            corpid=self.corpid, corpsecret=self.corpsecret)
        data = requests.get(url).json()
        if data.get('errcode') != 0:
            logging.error(data.get('errmsg'))
        return data.get('access_token')

    def get_userinfo(self, code):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={access_token}&code={code}'.format(
            access_token=self.access_token, code=code)
        data = requests.get(url).json()
        if data.get('errcode'):
            logging.error(data.get('errmsg'))
        return data.get('UserId')


    def get_user(self, userid):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={access_token}&userid={userid}'.format(access_token=self.access_token, userid=userid)
        data = requests.get(url).json()
        return {
            'username': data.get('userid'),
            'name': data.get('name'),
            'mobile': data.get('mobile'),
            'email': data.get('email')
        }
